package com.atguigu.lease.web.app.service.impl;



import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtil;
import com.atguigu.lease.web.app.service.LoginService;

import com.atguigu.lease.web.app.service.SmsService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.baomidou.mybatisplus.autoconfigure.DdlApplicationRunner.log;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsService smsService;
    @Override
    public void getCode(String phone) {
        //生成验证码
        String code = CodeUtil.getCode(6);
        smsService.sendCode(phone,code);


        //将验证码存入redis
        String key = RedisConstant.APP_LOGIN_PREFIX+phone;

//        Boolean hasKey = redisTemplate.hasKey(key);
//        if(hasKey){
//            Long ttl =redisTemplate.getExpire(key, TimeUnit.SECONDS);
//            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC-ttl<RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
//                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
//            }
//        }

        // 3. 异步发送短信，并将验证码存入Redis

        CompletableFuture.runAsync(() -> {
            try {
                smsService.sendCode(phone, code);
            } catch (Exception e) {
                // 日志记录异常信息
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        });

        redisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);


    }
}
